//
//  HomeViewController.m
//  IWISHING
//
//  Created by Phan Ba Minh on 1/19/13.
//  Copyright (c) 2013 kidbaw. All rights reserved.
//

#import "HomeViewController.h"
#import "SupportFunction.h"
#import "Define.h"
#import <QuartzCore/QuartzCore.h>
#import "UserDataManager.h"
#import "AppViewController.h"
#import "SBJSON.h"
#import "PersonDataManager.h"
#import "UIImageView+WebCache.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if ([SupportFunction deviceIsIPad]) {
        self = [super initWithNibName:@"HomeViewController_IPAD" bundle:nibBundleOrNil];
    }
    else {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    }
    
    if (self) {
        // Custom initialization
        _APIRequester_Phongdep = [APIRequester new];
        _APIRequester = [APIRequester new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _isInitiationAtTheFirstTime = YES;
}

- (void)viewDidUnload {
    [self setBtnStart:nil];
    [self setViewPhongDepBanner01:nil];
    [self setViewPhongDepBanner02:nil];
    [self setImageViewPhongDepBanner01_Avatar:nil];
    [self setLblPhongDepBanner01_Name:nil];
    [self setLblPhongDepBanner01_Price:nil];
    [self setLblPhongDepBanner01_Address:nil];
    [self setImageViewPhongDepBanner02_Avatar:nil];
    [self setLblPhongDepBanner02_Name:nil];
    [self setLblPhongDepBanner02_Price:nil];
    [self setLblPhongDepBanner02_Address:nil];
    [self setBtnAddress:nil];
    [self setBtnEmail:nil];
    [self setBtnFacebook:nil];
    [self setBtnHotline01:nil];
    [self setBtnHotline02:nil];
    [self setImageViewPhongDepBanner01_Status:nil];
    [self setImageViewPhongDepBanner02_Status:nil];
    [self setBtnPhongDepBanner01_Status:nil];
    [self setBtnPhongDepBanner02_Status:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_isInitiationAtTheFirstTime) {
        // INTERFACE
        [self initInterface];
        [self loadInterface];
        
        _isInitiationAtTheFirstTime = NO;
    }
    
    _isRequestingTheNext = YES;
    _offsetMain = 0;
    [self requestTheNext];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initInterface {
    _heightAdBanner = HEIGHT_AD_BANNER;
    if ([SupportFunction deviceIsIPad]) {
        _heightAdBanner = HEIGHT_AD_BANNER_LANDSCAPE_IPAD;
    }
    
    // ADS MANAGER
    _adsManager = [KIDBAWAdvertisementManager new];//iAds
    [_adsManager startAdsInView:self andBannerFrame:CGRectMake(0, 0, self.view.frame.size.width, _heightAdBanner) andDelegate:self];
    
    // PHONGDEP BANNERS
    _viewPhongDepBanner01.frame = CGRectOffset(_viewPhongDepBanner01.frame, 0, _heightAdBanner);
    [self.view addSubview:_viewPhongDepBanner01];
    _viewPhongDepBanner01.hidden = YES;
    _viewPhongDepBanner02.frame = CGRectOffset(_viewPhongDepBanner02.frame, 0, _heightAdBanner);
    [self.view addSubview:_viewPhongDepBanner02];
    _viewPhongDepBanner02.hidden = YES;
}
- (void)loadInterface {
    _arrayMain = [PersonDataManager roomsShared].categoryArray;
}

- (void)loadNextBanner {
    if (_arrayMain.count == 0 || _phongdepBannerIndex > _arrayMain.count) {
        return;
    }
    
    // NODE 01
    PersonNodeData *roomNode01 = [_arrayMain objectAtIndex:_phongdepBannerIndex];
        // AVATAR
    [_imageViewPhongDepBanner01_Avatar setImageWithURL:[NSURL URLWithString:roomNode01.personSmallAvatarURL] placeholderImage:IMG_AVARTAR_DUMMY];
    
        // NAME
    _lblPhongDepBanner01_Name.text = roomNode01.personName;
    
        // STATUS
    if (roomNode01.personPhongDepStatus.intValue > 0) {
        _imageViewPhongDepBanner01_Status.hidden = YES;
        _btnPhongDepBanner01_Status.hidden = NO;
        [_btnPhongDepBanner01_Status setTitle:STRING_REMAINING_DAY_FORMAT(roomNode01.personPhongDepStatus.intValue) forState:UIControlStateNormal];
    }
    else {
        _imageViewPhongDepBanner01_Status.hidden = NO;
        _btnPhongDepBanner01_Status.hidden = YES;
    }
    
        // PRICE
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.groupingSeparator = @".";
    numberFormatter.decimalSeparator = @",";
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    _lblPhongDepBanner01_Price.text = [NSString stringWithFormat:@"%@",
                       [numberFormatter stringFromNumber:[NSNumber numberWithFloat:roomNode01.personPhongDepPrice.floatValue]]];
    
        // ADDRESS
    NSString *address = roomNode01.personPhongDepAddress;
    NSString *district = roomNode01.personPhongDepDistrict;
    NSString *city = roomNode01.personPhongDepCity;
    _lblPhongDepBanner01_Address.text = STRING_ADDRESS_FORMAT(address, district, city);
    
    // NODE 2
    PersonNodeData *roomNode02 = nil;
    if (_phongdepBannerIndex + 1 < _arrayMain.count) {
        int randIndex = rand()%_arrayMain.count;
        if (randIndex == _phongdepBannerIndex) {
            randIndex = (randIndex + 1)%_arrayMain.count;
        }
        roomNode02 = [_arrayMain objectAtIndex:randIndex];
            // AVATAR
        [_imageViewPhongDepBanner02_Avatar setImageWithURL:[NSURL URLWithString:roomNode02.personSmallAvatarURL] placeholderImage:IMG_AVARTAR_DUMMY];
        
            // STATUS
        if (roomNode02.personPhongDepStatus.intValue > 0) {
            _imageViewPhongDepBanner02_Status.hidden = YES;
            _btnPhongDepBanner02_Status.hidden = NO;
            [_btnPhongDepBanner02_Status setTitle:STRING_REMAINING_DAY_FORMAT(roomNode01.personPhongDepStatus.intValue) forState:UIControlStateNormal];
        }
        else {
            _imageViewPhongDepBanner02_Status.hidden = NO;
            _btnPhongDepBanner02_Status.hidden = YES;
        }
        
            // NAME
        _lblPhongDepBanner02_Name.text = roomNode02.personName;
        
            // PRICE
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        numberFormatter.groupingSeparator = @".";
        numberFormatter.decimalSeparator = @",";
        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
        _lblPhongDepBanner02_Price.text = [NSString stringWithFormat:@"%@",
                                           [numberFormatter stringFromNumber:[NSNumber numberWithFloat:roomNode02.personPhongDepPrice.floatValue]]];
        
            // ADDRESS
        NSString *address = roomNode02.personPhongDepAddress;
        NSString *district = roomNode02.personPhongDepDistrict;
        NSString *city = roomNode02.personPhongDepCity;
        _lblPhongDepBanner02_Address.text = [NSString stringWithFormat:@"Địa chỉ: %@, %@, %@.",address,district,city];
    }
    
    CGRect frame01 = CGRectMake(-self.view.frame.size.width, _heightAdBanner, self.view.frame.size.width, _viewPhongDepBanner01.frame.size.height);
    CGRect frame02 = CGRectMake(0, _heightAdBanner, self.view.frame.size.width, _viewPhongDepBanner01.frame.size.height);
    CGRect frame03 = CGRectMake(self.view.frame.size.width, _heightAdBanner, self.view.frame.size.width, _viewPhongDepBanner01.frame.size.height);
    if (_phongdepBannerIndex == 0 || (roomNode01 && !roomNode02)) {
        _viewPhongDepBanner01.frame = frame03;
        _viewPhongDepBanner01.hidden = NO;
        _viewPhongDepBanner02.hidden = YES;
        
        [UIView  beginAnimations:nil context: nil];
        [UIView setAnimationDuration:TIMER_CHANGING_VIEW];
        _viewPhongDepBanner01.frame = frame02;
        [UIView commitAnimations];
    }
    else {
        _viewPhongDepBanner01.frame = frame02;
        _viewPhongDepBanner02.frame = frame03;
        _viewPhongDepBanner01.hidden = NO;
        _viewPhongDepBanner02.hidden = NO;
        
        [UIView  beginAnimations:nil context: nil];
        [UIView setAnimationDuration:TIMER_CHANGING_VIEW];
        _viewPhongDepBanner01.frame = frame01;
        _viewPhongDepBanner02.frame = frame02;
        [UIView commitAnimations];
    }
    
    _phongdepBannerIndex = (_phongdepBannerIndex + 1)%_arrayMain.count;
}

- (void)update {
    // iAd
    [_adsManager update];
    
    // PHONGDEP BANNERS
    if (_arrayMain.count > 0 && CFAbsoluteTimeGetCurrent() - _timeLoadNextBanner > TIMER_HIDING_BANNER) {
        [self loadNextBanner];
        _timeLoadNextBanner = CFAbsoluteTimeGetCurrent();
    }
}

#pragma mark - Actions

- (IBAction)touchUpInsideButton:(id)sender {
    if (sender == _btnStart) {
        [[AppViewController Shared] changeToMainPageViewController];
    }
    else if (sender == _btnEmail) {
        [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CONTACT_BY_EMAIL_01];
    }
    else if (sender == _btnFacebook) {
        [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_OPEN_URL_01];
    }
    else if (sender == _btnHotline01) {
//        [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_01];
        
//        NSString *phoneNumber = [@"telprompt://" stringByAppendingString:_btnHotline01.titleLabel.text];
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
        
        _selectedHotlineIndex = 0;
        ALERT_2(_btnHotline01.titleLabel.text, @"", self, @"Cancel", @"Call");
    }
    else if (sender == _btnHotline02) {
//        [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_02];
        
//        NSString *phoneNumber = [@"telprompt://" stringByAppendingString:_btnHotline01.titleLabel.text];
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
        
        _selectedHotlineIndex = 1;
        ALERT_2(_btnHotline02.titleLabel.text, @"", self, @"Cancel", @"Call");
    }
}

#pragma mark - APIRequesterProtocol

- (void)requestTheNext {
    if (_isRequesting) {
        return;
    }
    
    _isRequesting = YES;
    
    NSString *requestURL = STRING_REQUEST_URL_PHONGDEP_GET_ROOMS(_offsetMain, _limitMain);
    
    [_APIRequester_Phongdep requestWithType:ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOMS andRootURL:requestURL andPostMethodKind:YES andParams:nil andDelegate:self];
    
//#ifdef __DEBUG__
//    NSLog(@"requestTheNext: %@", requestURL);
//#endif
}

- (void)requestWithType:(ENUM_API_REQUEST_TYPE)requestType {
    // USER ID
    NSString *userID = @"";
    
    // USER NAME
    NSString *userName = @"";
    
    // DEVICE UDID
    NSString *deviceUDID = [UIDevice currentDevice].deviceUDID;
    [UserDataManager Shared].userDeviceUDID = deviceUDID;
    
    
    // DEVICE TOKEN
    NSString *deviceToken = @"";
    if ([UserDataManager Shared].userRegisteredDeviceToken) {
        deviceToken = [UserDataManager Shared].userRegisteredDeviceToken;
        [UserDataManager Shared].userDeviceToken = [UserDataManager Shared].userRegisteredDeviceToken;
    }
    
    // ENTER FOREGROUND APP
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:deviceToken forKey:STRING_REQUEST_KEY_DEVICE_TOKEN];
    [params setValue:deviceUDID forKey:STRING_REQUEST_KEY_DEVICE_UDID];
    [params setValue:userID forKey:STRING_REQUEST_KEY_USER_ID];
    [params setValue:userName forKey:STRING_REQUEST_KEY_USER_NAME];
    [params setValue:[NSString stringWithFormat:@"%i", [UIDevice currentDevice].platformType] forKey:STRING_REQUEST_KEY_DEVICE_TYPE];
    [params setValue:[UIDevice currentDevice].platformString forKey:STRING_REQUEST_KEY_DEVICE_NAME];
    
    switch (requestType) {
        case ENUM_API_REQUEST_TYPE_ACTIONS_CONTACT_BY_EMAIL_01: {
            [params setValue:_btnEmail.titleLabel.text forKey:STRING_REQUEST_KEY_EMAIL_NAME];
            
#ifdef __DEBUG__
            NSLog(@"CONTACT BY EMAIL 01: %@", params);
#endif
            [_APIRequester requestWithType:requestType andRootURL:STRING_REQUEST_URL_ACTIONS_CONTACT_BY_EMAIL_01 andPostMethodKind:YES andParams:params andDelegate:self];
            
            // TODO:
            [[AppViewController Shared] changeToFeedbackVCWithEmailAddress:_btnEmail.titleLabel.text];
            break;
        }
            
        case ENUM_API_REQUEST_TYPE_ACTIONS_OPEN_URL_01: {
            [params setValue:_btnFacebook.titleLabel.text forKey:STRING_REQUEST_KEY_URL_NAME];
            
#ifdef __DEBUG__
            NSLog(@"OPEN URL 01: %@", params);
#endif
            [_APIRequester requestWithType:requestType andRootURL:STRING_REQUEST_URL_ACTIONS_OPEN_URL_01 andPostMethodKind:YES andParams:params andDelegate:self];
            
            // TODO:
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@", _btnFacebook.titleLabel.text]]];
            break;
        }
            
        case ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_01: {
            [params setValue:_btnHotline01.titleLabel.text forKey:STRING_REQUEST_KEY_PHONE_FROM_NUMBER];
            [params setValue:_btnHotline01.titleLabel.text forKey:STRING_REQUEST_KEY_PHONE_TO_NUMBER];
            
#ifdef __DEBUG__
            NSLog(@"CALL PHONE 01: %@", params);
#endif
            [_APIRequester requestWithType:requestType andRootURL:STRING_REQUEST_URL_ACTIONS_CALL_PHONE_01 andPostMethodKind:YES andParams:params andDelegate:self];
            
            // TODO:
            NSString *phoneNumber = [@"tel://" stringByAppendingString:_btnHotline01.titleLabel.text];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
            break;
        }
            
        case ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_02: {
            [params setValue:_btnHotline02.titleLabel.text forKey:STRING_REQUEST_KEY_PHONE_FROM_NUMBER];
            [params setValue:_btnHotline02.titleLabel.text forKey:STRING_REQUEST_KEY_PHONE_TO_NUMBER];
            
#ifdef __DEBUG__
            NSLog(@"CALL PHONE 02: %@", params);
#endif
            [_APIRequester requestWithType:requestType andRootURL:STRING_REQUEST_URL_ACTIONS_CALL_PHONE_02 andPostMethodKind:YES andParams:params andDelegate:self];
            
            // TODO:
            NSString *phoneNumber = [@"tel://" stringByAppendingString:_btnHotline02.titleLabel.text];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
            break;
        }
            
        default:
            break;
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    _isRequesting = NO;
    
//#ifdef __DEBUG__
//    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
#ifdef __DEBUG__
#else
        if (type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        }
#endif
        return;
    }
    
    NSMutableDictionary *jsonData = [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_DATA];
    
    if (!jsonData || jsonData.count == 0) {
        return;
    }
    
    if (type == ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOMS) {
        [[PersonDataManager roomsShared] resetAllData];
        
        int checkToGetTotal_Index = 0;
        int addedItems_Index = 0;
        for (NSString *key in jsonData.allKeys) {
            NSMutableDictionary *dicJson = [jsonData objectForKey:key];
            PersonNodeData *roomNode = [[PersonNodeData alloc] initWithPersonName:key andPersonID:[dicJson objectForKey:STRING_RESPONSE_KEY_ROOM_ID] andPersonSmallAvatar:nil];
            roomNode.personPhongDepStatus = [dicJson objectForKey:STRING_RESPONSE_KEY_STATUS];
            roomNode.personSmallAvatarURL = [dicJson objectForKey:STRING_RESPONSE_KEY_IMAGE];
            roomNode.personPhongDepArea = [dicJson objectForKey:STRING_RESPONSE_KEY_AREA];
            roomNode.personPhongDepPrice = [dicJson objectForKey:STRING_RESPONSE_KEY_PRICE];
            roomNode.personPhongDepAddress = [dicJson objectForKey:STRING_RESPONSE_KEY_ADDRESS];
            roomNode.personPhongDepDistrict = [dicJson objectForKey:STRING_RESPONSE_KEY_DISTRICT];
            roomNode.personPhongDepCity = [dicJson objectForKey:STRING_RESPONSE_KEY_CITY];
            
            // CHECK TO ADD: PREVIOUS ITEMS OR NEXT ITEMS
            if ([[PersonDataManager roomsShared] addNode:roomNode] == eIsDataAddSuccess) {
                addedItems_Index++;
            }
            
            // CHECK TO UPDATE ANIMATION ARROW & OFFSET FOR LOADING PREVIOUS/NEXT ITEMS
            if (checkToGetTotal_Index == 0) {
                //                _offsetMain = roomNode.puzzleHighScoreRank.integerValue - 1;
                //                _tableCellTotal = roomNode.puzzleHighScoreTotal.integerValue;
            }
            checkToGetTotal_Index++;
        }
        
        if (_isRequestingTheNext) {
            _offsetMain += addedItems_Index;
        }
        else {
            _offsetMain += _arrayMain.count;
        }
        [self loadInterface];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    _isRequesting = NO;
    
//#ifdef __DEBUG__
//    NSLog(@"requestFailed %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable] && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

#pragma mark - ALERT

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if (_selectedHotlineIndex == 0) {
            [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_01];
        }
        else if (_selectedHotlineIndex == 1) {
            [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_02];
        }
    }
}

@end
